package com.kkb.dynamiproxy;

import com.kkb.aop.AOP;
import com.kkb.aop.LogAOP;
import com.kkb.aop.TranAOP;
import com.kkb.service.BookService;
import com.kkb.service.IService;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class ProxyFactory {
    private IService service;
    private AOP aop;

    public ProxyFactory(IService service, AOP aop) {
        this.service = service;
        this.aop = aop;
    }

    /*获取动态代理示例*/
    public Object getProxyInstance(){
        return Proxy.newProxyInstance(
                service.getClass().getClassLoader(),
                service.getClass().getInterfaces(),
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        try {
                            aop.before();
                            Object invoke = method.invoke(service, args);//核心业务
                            aop.after();
                            return invoke;
                        } catch (IllegalAccessException e) {
                            aop.exception();
                            e.printStackTrace();
                            throw e;
                        } finally {
                            aop.myFinally();
                        }
                    }
                }
        );
    }

    public static void main(String[] args) {
        BookService bookService = new BookService();
        AOP tranAOP = new TranAOP();
        AOP logAOP = new LogAOP();

        //获取代理对象
        IService service = (IService) new ProxyFactory(bookService,tranAOP).getProxyInstance();//一级代理
        IService service1 = (IService) new ProxyFactory(service,logAOP).getProxyInstance();//二级代理
        //核心业务+服务代码混合在一起的完整的业务方法
        service1.add();


    }
}
